#include <iostream>
#include <fstream>
#include <cstdio>
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>

using namespace std;

struct TiledScreen {
  unsigned char s[16][41]; //The 41th Byte should be a LF...
};

SDL_Surface *display;

int main(int argc, char *argv[]) {
  FILE *in;
  TiledScreen screen;
  SDL_Surface *tileset;
  SDL_Rect drect, srect;
  SDL_Event event;

  if(argc != 2) {
    cerr << "Usage: display_a_screen filename\n";
    return 1;
  }
  if((in = fopen(argv[1], "r")) == NULL) {
    perror("Error while opening file!");
    return 2;
  } else {
    if(fread(&screen.s, 1, sizeof(screen.s), in) < 40 * 16) {
      cerr << "Error! Not enough bytes read!\n";
      return 2;
    }
    fclose(in);
  }
  if(SDL_Init(SDL_INIT_VIDEO) == -1) {
    cerr << "Can not initialise SDL!\n";
    return 3;
  }
  if((tileset = IMG_Load("hero2.tiles.png")) == NULL) {
    cerr << "SDL Error: " << SDL_GetError() << endl;
    return 4;
  }
  for(int y = 0; y < 16; ++y) {
    for(int x = 0; x < 40; ++x) {
      printf("%02X ", screen.s[y][x]);
    }
    putchar('\n');
  }
  if((display = SDL_SetVideoMode(640, 400, 32, SDL_DOUBLEBUF)) == NULL) {
    cerr << "Can not open display: " << SDL_GetError() << endl;
    return 5;
  }
  srect.x = 0;
  srect.w = 16;
  srect.h = 16;
  drect.w = 16;
  drect.h = 16;
  for(int y = 0; y < 16; ++y) {
    for(int x = 0; x < 40; ++x) {
      int tilenum = screen.s[y][x];
      srect.y = tilenum * 16;
      drect.x = x << 4;
      drect.y = y << 4;
      SDL_BlitSurface(tileset, &srect, display, &drect);
    }
  }
  SDL_Flip(display);
  SDL_Delay(1000);
  while(SDL_WaitEvent(&event)) {
    if(event.type == SDL_QUIT) break;
  }
  SDL_Quit();
  return 0;
}

//g++ display_a_screen.cc -lSDL -lSDL_image -lpthread
